package com.flexdms.i18n;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Logger;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIOutput;
import javax.faces.component.UIParameter;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.omnifaces.util.Faces;

public class LocalizationHelper
{
	public static final String NOT_LOCALIZED="notlocalized";
	public static final Logger logger=Logger.getLogger(DefaultResourceImpl.class.getName());

	public static Object[] getParamaters(UIComponent component)
	{
		List<Object> parameterList = null;

		if (component.getChildCount() > 0)
		{
			parameterList = new ArrayList<Object>(component.getChildCount());
			for (UIComponent kid : component.getChildren())
			{
				if (!(kid instanceof UIParameter))
				{
					continue;
				}
				parameterList.add(((UIParameter) kid).getValue());
			}
		}
		if (parameterList == null)
		{
			return null;
		}
		return parameterList.toArray();
	}
	
	public static String getStringValue(UIOutput component)
	{
		FacesContext context = FacesContext.getCurrentInstance();

		Converter converter = component.getConverter();
		Object value = component.getValue();
		if (value == null)
		{
			return null;
		}

		if (value instanceof String)
		{
			return (String) value;
		}
		Application application = context.getApplication();
		converter = (application.createConverter(value.getClass()));
		if (converter == null)
		{
			return value.toString();
		}
		return converter.getAsString(context, component, value);

	}

	public static ResourceBundle getBundle(UIComponent source)
	{
		I18NMessage i18nMessage=I18NMessage.getDatabaseI18nMessage();
		Locale locale=i18nMessage.getCurrentLocale();
		if (source.getAttributes().get("locale")!=null)
		{
			locale=I18NMessage.stringToLocale(source.getAttributes().get("locale").toString());
		}
		ResourceBundle resourceBundle = i18nMessage.loadBundle(locale);
		return resourceBundle;
	}
	public static String getLocalizedMessage(UIOutput source)
	{
		String value=getStringValue(source);
		if (value==null)
		{
			return "";
		}
		String string= (String) source.getAttributes().get(NOT_LOCALIZED);
		Boolean notlocalize = false;
		if (string!=null)
		{
			notlocalize=Boolean.valueOf(string);
		}
		if (notlocalize == null|| !notlocalize)
		{
			ResourceBundle resourceBundle=getBundle(source);
			value= resourceBundle.getString(value);
		}
		 

		Object[] params = getParamaters(source);
		if (params == null || params.length == 0)
		{
			return value;
		}

		MessageFormat formatter = new MessageFormat(value, FacesContext.getCurrentInstance().getViewRoot().getLocale());
		return formatter.format(params);
	}
	
	public static com.flexdms.i18n.FacesMessage processFacesMessage(FacesMessage msg1)
	{
		I18NMessage i18nMessage=I18NMessage.getDatabaseI18nMessage();
		DefaultResourceImpl impl=(DefaultResourceImpl) i18nMessage.loadBundle(i18nMessage.getCurrentLocale());
		
		com.flexdms.i18n.FacesMessage msg=null;
		if (msg1 instanceof com.flexdms.i18n.FacesMessage)
		{
			msg=(com.flexdms.i18n.FacesMessage) msg1;
		} else {
			msg=com.flexdms.i18n.FacesMessage.fromFacesMessage(msg1);
		}
	
		if (!msg.isShouldTranslate())
		{
			return msg;
		}
		if (msg.isTranslated())
		{
			return msg;
		}
		String summary=msg.getSummary();
		String detail=msg.getDetail();
		//static look up from resource bundle
		if (msg.isStaticText())
		{
			if (summary!=null && summary.length()>0)
			{
				msg.setSummary(impl.getString(summary));
			}
			if (detail!=null && detail.length()>0)
			{
				msg.setDetail(impl.getString(detail));
			}
			msg.setTranslated(true);
			return msg;
		}
		
		//using tempoary translation
		if (summary!=null && summary.length()>0)
		{
			try
			{
				//message format is keyed to
				if (BaseTranslator.isMessageFormat(summary))
				{
					summary=impl.getString(summary);
				} else {
					summary=impl.getTempTranslation(summary);
				}
						
				if (msg.getParams()!=null && msg.getParams().length>0)
				{
					MessageFormat format=new MessageFormat(summary, i18nMessage.getCurrentLocale());
					if (msg.isTranslateParams())
					{
						summary=format.format(translateParams(impl, msg.getParams()));
					} else {
						summary=format.format(msg.getParams());
					}
				}
				msg.setSummary(summary);
				msg.setTranslated(true);
			} catch (Exception e)
			{
				logger.info(e.getMessage());
			}
		}
	
		if (detail!=null && detail.length()>0)
		{
			try
			{
				//message format is keyed to
				if (BaseTranslator.isMessageFormat(detail))
				{
					detail=impl.getString(detail);
				} else {
					detail=impl.getTempTranslation(detail);
				}
				if (msg.getParams()!=null && msg.getParams().length>0)
				{
					MessageFormat format=new MessageFormat(detail, i18nMessage.getCurrentLocale());
					if (msg.isTranslateParams())
					{
						detail=format.format(translateParams(impl, msg.getParams()));
					} else {
						detail=format.format(msg.getParams());
					}
					
					
				}
				msg.setDetail(detail);
				msg.setTranslated(true);
			} catch (Exception e)
			{
				logger.info(e.getMessage());
			}
		}
	
		return msg;
	}
	
	
	public static String[] translateParams(DefaultResourceImpl impl, Object params[])
	{
		String[] retStrings=new String[params.length];
		int count=0;
		for(Object obj: params)
		{
			retStrings[count]=impl.getString(obj.toString());
			count++;
		}
		return retStrings;
	}

}
